import json
import requests


class BaiDuFanYi:
    def __init__(self):
        # UA伪装
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36'}
        # 百度翻译提交数据的网址
        self.url = 'https://fanyi.baidu.com/sug'

    def enter(self, keyword):  # 要翻译的词语
        # post方法提交的数据
        data = {'kw': keyword}
        r = requests.post(self.url, data=data, headers=self.headers)
        dic = r.json()
        self.write(dic)
        '''
                {'errno': 0, 'data': [{'k': 'good', 'v': 'adj. 好的; 优秀的; 有益的; 漂亮的，健全的 n. 好处，利益; 善良; 善行; 好人 ad'}, {'k': 'Good', 'v': '[人名] [英格兰人姓氏] 古德绰号，来源于中世纪英语，含义是“好”(good); [人名] [英格'}, {'k': 'GOOD', 'v': 'abbr. graph-oriented object database 面向图形的目标数据库'}, {'k': 'Good.', 'v': '很好。'}, {'k': 'Goode', 'v': '[人名] [英格兰人姓氏] 古德 Good的变体; [地名] [美国] 古德'}]}
        '''
        return dic

    def printf(self, keyword):
        # print(result)
        # 提取翻译结果
        if keyword:
            result = self.enter(keyword)['data']
            n = 0
            for i in range(0, len(result)):
                n += 1
                print(n, result[i]["v"])
        else:
            TypeError("keyword mast is str and is not ''")

    def write(self, dic):
        # print(result)
        # 持久化存储
        JsonData = json.loads(open("JSON/BaiDuFanYi/1.json", "r").read())
        with open("JSON/BaiDuFanYi/1.json", "w") as f:
            len_Json_Data = len(JsonData)
            JsonData[len_Json_Data] = dic
            f.write(json.dumps(JsonData))


q = None
p = BaiDuFanYi()
while q != "":
    q = input("enter word>")
    if q == "":
        pass
    else:
        p.printf(q)
